<template>
  <div class="main">
    <div class="login-container">
      <div class="login-card">
        <div class="logo-section">
          <div class="logo"></div>
          <h1 class="title">中享思途-健身会馆</h1>
          <p class="subtitle">ZHONGXIANG SITU FITNESS CLUB</p>
        </div>

        <div class="form-section">
          <el-form :model="loginFormModel" :rules="rules" ref="loginFormRef" @keydown.enter="submitLogin">
            <el-form-item prop="phone">
              <el-input
                  v-model="loginFormModel.phone"
                  placeholder="请输入手机号"
                  prefix-icon="User"
                  size="large"
                  class="custom-input"
                  autocomplete="off"/>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                  type="password"
                  v-model="loginFormModel.password"
                  show-password
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                  size="large"
                  class="custom-input"
                  autocomplete="off"/>
            </el-form-item>

            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input
                    placeholder="验证码"
                    v-model="loginFormModel.captcha"
                    maxlength="4"
                    minlength="4"
                    size="large"
                    class="captcha-input"
                    autocomplete="off"/>
                <img
                    class="captcha"
                    :src="captchaUrl"
                    @click="refresh"
                    alt="验证码">
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  class="login-btn"
                  @click="submitLogin"
                  size="large"
                  :loading="loginLoading">
                登录
              </el-button>
            </el-form-item>

            <el-form-item>
              <el-button
                  type="success"
                  class="register-btn"
                  @click="registerDlgShow=true"
                  size="large"
                  link>
                立即注册
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <div class="copyright">
      &copy; 2025 版权所有 中享思途-健身会馆
    </div>
  </div>

  <!--注册对话框-->
  <div>
    <el-dialog
        title="用户注册"
        v-model="registerDlgShow"
        width="500px"
        class="register-dialog"
        :before-close="handleClose">
      <el-form ref="registerForm" :model="registerModel" :rules="registerRules">
        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="registerModel.phone"
              placeholder="请输入手机号"
              size="large"/>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              type="password"
              v-model="registerModel.password"
              show-password
              placeholder="请输入密码"
              size="large"/>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              type="password"
              v-model="registerModel.confirmPassword"
              show-password
              placeholder="请再次输入密码"
              size="large"/>
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select
              v-model="registerModel.role"
              placeholder="请选择角色"
              size="large"
              style="width: 100%">
            <el-option label="会员" value="member"></el-option>
            <el-option label="教练" value="coach"></el-option>
            <el-option label="普通管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input
              type="text"
              v-model="registerModel.name"
              placeholder="请输入您的姓名"
              size="large"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="registerDlgShow=false">取消</el-button>
          <el-button type="primary" @click="doRegister">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.main {
  height: 100vh;
  background: url("@/assets/login_bg.jpg") no-repeat center center/cover;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.main::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.4);
}

.login-container {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 450px;
  padding: 0 20px;
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  backdrop-filter: blur(10px);
  animation: fadeInUp 0.6s ease-out;
}

.logo-section {
  background: linear-gradient(120deg, #16b777, #00c9b7);
  padding: 40px 20px;
  text-align: center;
  color: white;
}

.logo {
  width: 80px;
  height: 80px;
  margin: 0 auto 15px;
  background: url("@/assets/img_1.png") no-repeat center center/cover;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 5px;
}

.subtitle {
  font-size: 12px;
  opacity: 0.9;
  margin: 0;
  letter-spacing: 1px;
}

.form-section {
  padding: 30px;
}

.custom-input :deep(.el-input__wrapper) {
  border-radius: 50px;
  padding: 10px 20px;
  box-shadow: 0 0 0 1px #e0e0e0 inset;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #16b777 inset;
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha {
  width: 120px;
  height: 40px;
  border-radius: 6px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
}

.login-btn {
  width: 100%;
  border-radius: 50px;
  height: 45px;
  font-size: 16px;
  background: linear-gradient(to right, #16b777, #00c9b7);
  border: none;
  margin-top: 10px;
}

.register-btn {
  width: 100%;
  border-radius: 50px;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

.copyright {
  position: absolute;
  bottom: 30px;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  z-index: 1;
}

.register-dialog :deep(.el-dialog__header) {
  background: linear-gradient(120deg, #16b777, #00c9b7);
  color: white;
  padding: 20px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.register-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 500;
}

.register-dialog :deep(.el-dialog__body) {
  padding: 30px 30px 10px;
}

.dialog-footer {
  text-align: center;
  padding: 20px;
}

.dialog-footer .el-button {
  min-width: 100px;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .login-card {
    margin: 0 15px;
  }

  .logo-section {
    padding: 30px 15px;
  }

  .form-section {
    padding: 20px;
  }

  .captcha {
    width: 100px;
    height: 38px;
  }
}
</style>

<script setup>
import { ref, reactive, toRaw } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { login } from "@/api/user.js";
//生成随机数
import { v4 as uuid } from "uuid";
import { saveJwt } from "@/api/jwt.js";
import router from "@/router/index.js";
import api from "@/util/api.js";

//验证码地址
const captchaUrl = ref("/api/users/captcha");
const loginLoading = ref(false);
const registerDlgShow = ref(false);

const registerModel = reactive({
  phone: null,
  password: null,
  confirmPassword: null,
  name: null,
  role: null
});

const registerForm = ref();
// 添加JWT解码函数
function parseJwt(token) {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error("解析JWT失败:", error);
    return null;
  }
}
//注册表单验证规则
const registerRules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码至少6位", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerModel.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  role: [
    { required: true, message: "请选择角色", trigger: "change" }
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" }
  ]
};

async function doRegister() {
  registerForm.value.validate(async (valid) => {
    if (valid) {
      const params = toRaw(registerModel);
      delete params.confirmPassword; // 删除确认密码字段

      try {
        const resp = await api({
          url: "/users/register",
          method: "post",
          data: params
        });

        if (resp.success) {
          ElMessage.success("注册成功");
          registerDlgShow.value = false;
          // 重置表单
          Object.keys(registerModel).forEach(key => {
            registerModel[key] = null;
          });
        } else {
          ElMessage.error(resp.error || "注册失败");
        }
      } catch (error) {
        ElMessage.error("注册失败，请稍后重试");
      }
    }
  });
}

//刷新验证码
function refresh() {
  captchaUrl.value = "/api/users/captcha?id=" + Math.random();
}

//登录表单验证规则
const rules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" }
  ],
  password: [{
    required: true, message: "请输入密码", trigger: "blur"
  }],
  captcha: [{
    required: true, message: "请输入验证码", trigger: "blur"
  }, {
    min: 4, max: 4, message: "验证码必须为4位字符", trigger: "blur"
  }]
};

//登录数据模型
const loginFormModel = reactive({
  phone: "15963294666",
  password: "123456",
  captcha: ""
});

const loginFormRef = ref(); //表单实例引用

//提交登录
function submitLogin() {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loginLoading.value = true;
      try {
        const model = toRaw(loginFormModel);
        const resp = await login(model);

        if (resp.success) {
          //保存jwt
          saveJwt(resp.data);

          // 解析JWT获取用户角色
          const decoded = parseJwt(resp.data);
          const userRole = decoded?.role?.toLowerCase();
          // 将用户角色也保存到sessionStorage中，方便后续使用
          sessionStorage.setItem('userRole', userRole)          // 根据角色跳转到不同页面
          let routePath = "/main"; // 默认路径

          if (userRole === "admin") {
            routePath = "/main/admin";
          } else if (userRole === "coach") {
            routePath = "/main/teach";
          } else if (userRole === "member") {
            routePath = "/main/member-course";
          }

          //路由跳转
          router.push(routePath);
        } else {
          ElMessage.error(resp.error || "登录失败");
          refresh();
        }
      } catch (error) {
        ElMessage.error("登录失败，请稍后重试");
        refresh();
      } finally {
        loginLoading.value = false;
      }
    } else {
      ElMessage.error("请填写正确的登录信息");
      refresh();
    }
  });
}

// 关闭对话框前的确认
function handleClose(done) {
  ElMessageBox.confirm('确认关闭注册窗口吗？')
      .then(() => {
        done();
      })
      .catch(() => {
        // 取消关闭
      });
}
</script>
